package com.jh.fcsm.service.sys.impl;

import com.jh.fcsm.beans.sys.SysFileInfo;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.dao.sys.SysFileInfoMapper;
import com.jh.fcsm.enums.FileSource;
import com.jh.fcsm.util.io.FileUtil;
import com.jh.fcsm.util.security.UUIDUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDate;

/**
 * 本地存储文件<br>
 * 该实现文件服务只能部署一台<br>
 * 如多台机器间能共享到一个目录，即可部署多台
 *
 * @author szx
 */
@Service("localFileServiceImpl")
public class LocalFileServiceImpl extends AbstractFileService {

    /**
     * 路径分割符，采用window式风格 “/”
     */
    private static final String FILE_SEPARATOR = "/";
    @Autowired
    private SysFileInfoMapper fileDao;
    @Value("${file.local.urlPrefix}")
    private String urlPrefix;
    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.local.path}")
    private String localFilePath;

    @Value("${file.filePath}")
    private String filePath;

    @Override
    protected SysFileInfoMapper getFileDao() {
        return fileDao;
    }

    @Override
    protected FileSource fileSource() {
        return FileSource.LOCAL;
    }

    @Override
    protected SysFileInfo uploadLocalFile(File file, SysFileInfo fileInfo) throws Exception {
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);

        String suffix = "/" + LocalDate.now().toString() + "/" + UUIDUtils.getUUID() + fileSuffix;

        String path = localFilePath + suffix;
        String url = urlPrefix + suffix;

        // 复制文件
        FileUtils.copyFile(file, new File(path));

        fileInfo.setPath(path);
        fileInfo.setUrl(url);
        return fileInfo;
    }

    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo) throws Exception {
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);

        String suffix = "/" + LocalDate.now() + "/" + UUIDUtils.getUUID() + fileSuffix;

        String path = localFilePath + suffix;
        String url = urlPrefix + suffix;
        fileInfo.setPath(path);
        fileInfo.setUrl(url);

        FileUtil.saveFile(file, path);
    }

    /**
     * @param file
     * @param fileInfo
     * @param markPath 格式：330000/330500/330523/91330523MA2B549Q9F.txt
     *                 上传文件
     * @author szx
     */
    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo, String markPath) {
//        int index = fileInfo.getName().lastIndexOf(".");
        // 文件拓展名，包含“.”
//        String ext = index > -1 ? fileInfo.getName().substring(index) : "";

        // 文件路径
        StringBuilder sb = new StringBuilder(FILE_SEPARATOR);
        // 配置文件目录为blbConfig/
        sb.append("lscmsConfig" + FILE_SEPARATOR);
        if (!org.apache.commons.lang3.StringUtils.isEmpty(markPath)) {
            sb.append(markPath).append(FILE_SEPARATOR);
        }
//        sb.append(LocalDate.now().toString()).append(FILE_SEPARATOR);
        sb.append(fileInfo.getName());
        // 文件物理路径
        String path = localFilePath + sb;
        // 文件服务器路径
        String url = urlPrefix + sb;

        fileInfo.setPath(path);
        fileInfo.setUrl(url);
        FileUtil.saveFile(file, path);
    }

    @Override
    protected boolean deleteFile(SysFileInfo fileInfo) {
        return FileUtil.deleteFile(fileInfo.getPath());
    }

    /**
     * 下载文件 szx 增加
     */
    @Override
    public void down(String key, HttpServletResponse response) {
        if (StringUtils.isEmpty(key)) {
            throw new ServiceException("非法请求");
        }
        int buffer = 1024 * 10;
        byte[] data = new byte[buffer];
        int lastIn = key.lastIndexOf('/');
        String fileName = lastIn < 0 ? key : key.substring(lastIn);
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(key));
            // 设置excel的文件名称
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            response.setContentType("multipart/octet-stream");
            OutputStream out = response.getOutputStream();
            int read;
            while ((read = inputStream.read(data)) != -1) {
                out.write(data, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    @Override
    public boolean copyFile(String source, String taraget) {
        source = source.replace(filePath + urlPrefix, "");
        taraget = taraget.replace(filePath + urlPrefix, "");
        String sourceFilePath = localFilePath + source;
        String taragetFilePath = localFilePath + taraget;
        try {
            FileUtils.copyFile(new File(sourceFilePath), new File(taragetFilePath));
            return true;
        } catch (IOException e) {
            logger.error("copy文件失败", e);
        }

        return false;
    }
}
